package auctionhaus

class Listing {
    String name
    Date dateCreated
    Date endTime
    String description
    
    Customer seller
    Customer winner

    double startBid
    static hasMany = [bids: Bid]

    static constraints = {
        // make sure name can only be 64 chars and not blank
        name maxSize:  64, blank: false

        // make sure end time is not blank and is a date in the future
        endTime blank: false, validator: { valDate ->
            return valDate.after(new Date())
        }

        // make sure description is less than 256 chars and can be blank or null
        description maxSize: 256, blank: true, nullable: true

        // make sure the seller is not blank
        seller blank: false

        // make sure the winner can be nullable or blank since a listing may not have a winner yet
        winner blank: true, nullable: true

        // make sure it always has a starting bid
        startBid blank: false, validator: {
            it > 0.0
        }

        // make sure bids are at least .5 greater than previous
        bids validator: { incomingBids, instance ->
            def retVal = true
            if(incomingBids) {
                def allBids = incomingBids.sort {it.dateCreated}.reverse()
                double startBidValue = instance.startBid
                def previous = allBids[0]
                if(previous.amount < startBidValue) {
                    retVal = false
                }
                else {
                    allBids.each {
                        if(it.id != previous.id) {
                            if(it.amount < previous.amount + 0.5) {
                                retVal = false
                            }
                            previous = it
                        }
                    }
                }
            }
            return retVal
        }
    }
}
